package com.yang.system.application.orgMng.empService;

import com.yang.system.domain.orgMng.emp.Emp;
import com.yang.system.domain.orgMng.emp.Skill;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Component
public class EmpUpdator {
    public void update(Emp emp, UpdateEmpRequest request, User user) {
        emp.setNum(request.getNum());
        emp.setIdNum(request.getIdNum());
        emp.setDob(request.getDob());
        emp.setGender(Gender.ofCode(request.getGenderCode()));
        emp.setLastUpdatedAt(LocalDateTime.now());
        emp.setLastUpdatedBy(user.getId());
        emp.toUpdate();         // 设置修改状态

        updateSkills(emp, request, user.getId());
        updateExperiences(emp, request, user.getId());
    }

    // 对技能的增删改
    private void updateSkills(Emp emp, UpdateEmpRequest request
            , Long userId) {
        deleteAbsentSkills(emp, request);
        operatePresentSkills(emp, request, userId);
    }

    // 删除目前聚合里有，但请求参数里没有的技能
    private void deleteAbsentSkills(Emp emp, UpdateEmpRequest request) {
        emp.getSkills().forEach(presentSkill -> {
            if (request.isSkillAbsent(presentSkill)) {
                emp.deleteSkill(presentSkill.getSkillTypeId());
            }
        });
    }

    // 增加或修改技能
    private void operatePresentSkills(Emp emp
            , UpdateEmpRequest request, Long userId) {
        for (SkillDto skill : request.getSkills()) {
            Optional<Skill> skillMaybe = emp.getSkill(
                    skill.getSkillTypeId());
            if (skillMaybe.isPresent()) {
                emp.updateSkill(skill.getSkillTypeId()
                        , SkillLevel.ofCode(skill.getLevelCode())
                        , skill.getDuration()
                        , userId);
            } else {
                emp.addSkill(skill.getSkillTypeId()
                        , SkillLevel.ofCode(skill.getLevelCode())
                        , skill.getDuration()
                        , userId);
            }
        }

    }

    private void updateExperiences(Emp emp, UpdateEmpRequest request
            , Long userId) {
        // 与updateSkilL()类似...
    }

}

